package com.example.neartweet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.widget.Toast;

public class ComService extends Service {
	
	/** For showing and hiding our notification. */
    NotificationManager mNM;
    /** Keeps track of all current registered clients. */
    ArrayList<Messenger> mClients = new ArrayList<Messenger>();
    /** Holds last value set by a client. */
    int mValue = 0;
    
    final String host = "172.20.81.167";
    final int port = 8000;
    
    Bundle myB = new Bundle();
    private Socket clientSocket = new Socket();
    private static InputStreamReader inputStreamReader;
    private static BufferedReader bufferedReader;
    private static PrintWriter printWriter;
    
    private final IBinder bindas = new LB();

    @Override
    public void onCreate() {
        mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        
    }

    @Override
    public void onDestroy() {
        // Cancel the persistent notification.
        mNM.cancel(R.string.remote_service_started);
        
        try {
			clientSocket.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

        // Tell the user we stopped.
        Toast.makeText(this, R.string.remote_service_stopped, Toast.LENGTH_SHORT).show();
    }

    /**
     * When binding to the service, we return an interface to our messenger
     * for sending messages to the service.
     */
    @Override
    public IBinder onBind(Intent intent) {
    	return bindas;
    }

    /**
     * Show a notification while this service is running.
     */
    private void showNotification() {
        // In this sample, we'll use the same text for the ticker and the expanded notification
        CharSequence text = getText(R.string.remote_service_started);

        // Set the icon, scrolling text and timestamp
        Notification notification = new Notification(R.drawable.ic_launcher, text,
                System.currentTimeMillis());

        // The PendingIntent to launch our activity if the user selects this notification
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, NearTweet.class), 0);

        // Set the info for the views that show in the notification panel.
        notification.setLatestEventInfo(this, getText(R.string.remote_service_label),
                       text, contentIntent);

        // Send the notification.
        // We use a string id because it is a unique number.  We use it later to cancel.
        mNM.notify(R.string.remote_service_started, notification);
    }
    
    public String receiveMessages(final String str) {
    	new Thread(new Runnable() {
			
			@Override
			public void run() {
				printWriter.println(str);
				printWriter.flush();
			}
		}).start();
    	return "Message Sent";
    }

    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
    	
    	// Display a notification about us starting.
        showNotification();
    	new Thread(new Runnable() {
			
			@Override
			public void run() {
				try {
		    		clientSocket = new Socket(host, port);
		    		printWriter = new PrintWriter(clientSocket.getOutputStream());
		    		inputStreamReader =
		        			new InputStreamReader(clientSocket.getInputStream());
		        	bufferedReader =
		        			new BufferedReader(inputStreamReader);
		    	} catch (UnknownHostException e) {
		    		e.printStackTrace();
		    	} catch (IOException e) {
		    		e.printStackTrace();
		    	}
				
			}
		}).start();
    	
    	return START_STICKY;
    }

    public String register(final String username) {
    	    	
    	new Thread(new Runnable() {
			
			@Override
			public void run() {
				printWriter.println("Reg:" + username);
				printWriter.flush();
			}
		}).start();
    	
    	
    	return "User Registered.";
    }
    
    public void unRegister(final String username) {
    	
    	new Thread(new Runnable() {
			
			@Override
			public void run() {
				printWriter.println("Unreg:" + username);
				printWriter.flush();
			}
		}).start();
    	
    }
    
    public void ban(final String from, final String to) {
    	new Thread(new Runnable() {

    		@Override
    		public void run() {
    			printWriter.println("Flag:" + from + ":" + to);
    			printWriter.flush();
    		}
    		
    	}).start();
    }
    
    public void envia(String str) {
    	Intent intent = new Intent("message");
		intent.putExtra("msg", str);
		Log.i("Message Received", str);
		LocalBroadcastManager.getInstance(ComService.this).sendBroadcast(intent);
    }
    
    public String listen() {
    	new Thread(new Runnable() {
    		String str1 = null;
			@Override
			public void run() {
				while (true){
					try {
						str1 = bufferedReader.readLine();
						if (str1 == null)
							continue;
						else
							envia(str1);
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}).start();
    	
    	return "Listening for Messages";
    }
    
    public void flush() {
    	printWriter.flush();
    }
    
    public class LB extends Binder {
    	ComService getService() {
    		return ComService.this;
    	}
    }

}
